<template>
  <div>
    <h1>注册</h1>
    <van-form @submit="onSubmit">
      <van-field
        v-model="obj.username"
        name="用户名"
        label="用户名"
        placeholder="用户名"
        :rules="[{ required: true, message: '请填写用户名' }]"
      />
      <van-field
        v-model="obj.password"
        type="password"
        name="密码"
        label="密码"
        placeholder="密码"
        :rules="[{ required: true, message: '请填写密码' }]"
      />
      <van-field
        v-model="obj.phone"
        type="number"
        name="手机号"
        label="手机号"
        placeholder="手机号"
        :rules="[{ required: true, message: '请填写手机号' }]"
      />
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { Toast } from "vant";
export default {
  data() {
    return {
      obj: {},
    };
  },
  methods: {
    fn1() {
      return this.$axios({
        url: "http://localhost:2800/users",
        method: "get",
        params: { phone: this.obj.phone },
      });
    },
    fn2() {
      return this.$axios({
        url: "http://localhost:2800/users",
        method: "get",
        params: { username: this.obj.username },
      });
    },
    //判断输入的手机号是否已注册,用户名是否重复
    onSubmit(values) {
      this.$axios.all([this.fn1(), this.fn2()]).then(
        this.$axios.spread((res1, res2) => {
          console.log(res1, res2);
          if (res1.data.length > 0) {
            //已有手机
            Toast.fail("您的手机号已注册,请更换");
          } else if (res2.data.length > 0) {
            //已有用户名
            Toast.fail("您的用户名已注册,请更换");
          } else {
            //注册

            this.$axios({
              url: "http://localhost:2800/users",
              method: "POST",
              data: this.obj,
            }).then((res) => {
              console.log(res);
              this.obj = {};
              Toast.success("您已注册成功");
              this.$router.push({ name: "login" });
            });
          }
        })
      );
      // if (flag) {
      //   this.$axios({
      //     url: "http://localhost:2800/users",
      //     method: "POST",
      //     data: this.obj,
      //   }).then((res) => {
      //     this.obj = {};
      //     Toast.success("您已注册成功");
      //     this.$router.push({ name: "login" });
      //   });
      // } else {
      //   Toast.fail("您的手机号或用户名已注册,请更换");
      // }
    },
  },
};
</script>

<style></style>
